package com.xiaomaoguai.fcp.pre.kepler.router.handler.spi;

import com.xiaomaoguai.fcp.pre.kepler.router.buf.Buf;
import com.xiaomaoguai.fcp.pre.kepler.router.handler.handlers.RPCHandler;
import com.xiaomaoguai.fcp.pre.kepler.router.handler.HandlerInfo;
import com.xiaomaoguai.fcp.pre.kepler.router.handler.api.Handler;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class HandlerManager {

    private final static Handler<Buf> rpcHandler = new RPCHandler();
    private final static ConcurrentHashMap<String, Handler<?>> localhandlerMap = new ConcurrentHashMap<String, Handler<?>>();
    private final static ConcurrentHashMap<String, HandlerInfo> rpcHandlerMap = new ConcurrentHashMap<String, HandlerInfo>();

    public static int size() {
        return localhandlerMap.size();
    }

    @SuppressWarnings("rawtypes")
    public static Handler getHandler(String handlerName) {
        Handler handler = localhandlerMap.get(handlerName);
        return handler != null ? handler : (rpcHandlerMap.containsKey(handlerName) ? rpcHandler : null);
    }

    @SuppressWarnings("rawtypes")
    public static HandlerInfo getHandlerInfo(String handlerName) {
        Handler handler = localhandlerMap.get(handlerName);
        return handler != null ? handler.getHandlerInfo() : rpcHandlerMap.get(handlerName);
    }

    @SuppressWarnings("rawtypes")
    public static Handler getRPCHandler() {
        return rpcHandler;
    }

    public static void addLocalHandler(String handlerName, Handler<?> handler) {
        localhandlerMap.put(handlerName, handler);
    }

    public static void addRpcHandler(HandlerInfo handlerInfo) {
        rpcHandlerMap.put(handlerInfo.getHandlerName(), handlerInfo);
    }

    public static void remove(String handlerName) {
        localhandlerMap.remove(handlerName);
        rpcHandlerMap.remove(handlerName);
    }

    public static boolean isRPCHandler(String handlerName) {
        return rpcHandlerMap.containsKey(handlerName);
    }

    public static List<HandlerInfo> getLocalHandlers() {
        return localhandlerMap.entrySet().stream()
                .map(entry -> entry.getValue().getHandlerInfo())
                .collect(Collectors.toList());
    }

}
